<template>
  <Form class="xtx-form" :validation-schema="rules" v-slot="{errors }" ref="fm">
    <div class="user-info">
      <img :src="QQuser.photo" />
      <p>Hi，{{QQuser.name}}   欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
        v-model="formData.mobile"
        name="mobile"
        :class="{err:errors.mobile}"
        class="input"
        type="text"
        placeholder="绑定的手机号" />
      </div>
      <div class="error" v-show="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
        v-model="formData.code"
        name="code"
        :class="{err:errors.code}"
        class="input"
        type="text"
        placeholder="短信验证码" />
        <span class="code" @click="handlerCode">{{count===0?'发送验证码':`${count}秒后从来`}}</span>
      </div>
        <div class="error" v-show="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
// import { useStore, useRouter } from 'vuex'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { useCountDown } from '@/hooks'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { message } from '@/components/Message/index.js'
import schema from '@/utils/vee-validate-schema'
const userQQ = () => {
  const QQuser = ref({
    name: '',
    photo: ''
  })
  if (window.QC.Login.check()) {
    window.QC.api('get_user_info').success((res) => {
      // console.log(res)
      QQuser.value.name = res.data.nickname
      QQuser.value.photo = res.data.figureurl_1
    })
  }

  return { QQuser }
}

const useValueFormData = () => {
  const formData = reactive({
    mobile: '',
    code: ''
  })
  // 校验规则
  const rules = {
    mobile: schema.mobile,
    code: schema.code
  }
  return { formData, rules }
}

const useSendCode = (formData) => {
  const fm = ref()
  // 使用倒计时函数
  const { count, start } = useCountDown(60)
  const handlerCode = async () => {
    const valueDate = schema.mobile(formData.mobile)
    if (valueDate === true) {
      // console.log('手机号没问题 发送验证码')
      if (count.value === 0) {
        try {
          await userQQBindCode(formData.mobile)
          message({ type: 'success', text: '发送成功！' })
          // 发完请求，开始倒计时
          start()
        } catch (error) {
          message({ type: 'error', text: error.response.data.message })
        }
      }
    } else {
      fm.value.setFieldError('mobile', valueDate)
    }
  }
  return { handlerCode, fm, count }
}

// QQ号绑定小兔鲜儿账号
const useSubmit = (fm, props, formData) => {
  const store = useStore()
  const router = useRouter()
  // 点击绑定的事件回调
  const bindQQ = async () => {
    /**
     * 1. 表单整体校验
     * 2. 校验通过执行绑定=》获取登录人信息存储=》跳首页
     */
    const res = await fm.value.validate()
    // console.log(res)
    if (res.valid) {
      try {
        // 校验通过
        const { result } = await userQQBindLogin({
          unionId: props.unionId,
          ...formData
        })
        // 存储当前登录人信息
        await store.commit('user/setProfile', result)
        // 登录成功之后=》合并之前本地购物车数据，到当前登录人名下
        await store.dispatch('cart/mergeCartAction')
        message({ type: 'success', text: 'QQ绑定成功！' })
        router.replace('/')
      } catch (error) {
        message({ type: 'error', text: 'QQ绑定失败！' })
      }
    }
  }

  return { bindQQ }
}
export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: {
    Form,
    Field
  },
  setup (props) {
    const { QQuser } = userQQ()
    const { formData, rules } = useValueFormData()
    const { handlerCode, fm, count } = useSendCode(formData)
    const { bindQQ } = useSubmit(fm, props, formData)
    return { QQuser, formData, rules, handlerCode, fm, count, bindQQ }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
